<template>
  <div class="mt10">
    <van-form @submit="onSubmit" @failed="onFail" ref="form">
      <van-field
        v-model="form.username"
        name="username"
        label="用户名称"
        clearable
        placeholder="请输入用户名称"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />

      <van-field
        v-model="form.password"
        name="password"
        label="登录密码"
        clearable
        placeholder="请输入登录密码"
        :type="type"
        :right-icon="type == 'password' ? 'closed-eye' : 'eye-o'"
        @click-right-icon="changeType"
        :rules="[
          { required: true, message: '请填写密码' },
          {
            pattern: reg.pwd,
            message: '请输入6-16的数字字母组合',
          },
        ]"
      />
      <div class="links">
        <p class="left">
          <router-link to="/register">没有账号,去注册?</router-link>
        </p>
        <p class="right">
          <router-link to="/forgetpass">找回密码?</router-link>
        </p>
      </div>
      <div style="margin: 16px">
        <van-button block type="primary" native-type="submit">提交</van-button>
      </div>
    </van-form>
  </div>
</template>




<script>
export default {
  data() {
    return {
      form: {},
      type: "password",
    };
  },
  methods: {
    changeType() {
      this.type = this.type == "password" ? "text" : "password";
    },
    async onSubmit(value) {
      let res = await this.$ajax.findUser(value);
      console.log(res);
      if (res.length > 0) {
        this.changeUserInfo(res[0]);
        localStorage.setItem("username", value.username);
        this.$router.push({
          name: "mine",
        });
      } else {
        this.$toast("登录失败，用户名或者密码错误");
      }
    },
    onFail() {
      this.showErrMsg("校验失败");
    },
  },
  mounted() {
    if (this.$route.query.username) {
      this.form = { ...this.form, username: this.$route.query.username };
    }else{
       this.form = { ...this.form, username: localStorage.getItem('username')};
    }
  },
};
</script>

<style lang="scss" scoped>
.links {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  .left a {
    color: #f50;
  }
  .right a {
    color: #123456;
  }
}
</style>